<!--角色-->
<!--chenyi 2019-10-11 23:06:01-->
<template>
  <div>
    <!--搜索条件-->
    <el-form inline :model="searchParam" ref="searchParam" label-width="80px" class="search-form">
      <el-form-item label="角色编码" prop="roleCode">
        <el-input v-model="searchParam.roleCode" placeholder="角色编码" clearable></el-input>
      </el-form-item>
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="searchParam.roleName" placeholder="角色名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="是否内置" prop="isSys">
        <es-select v-model="searchParam.isSys" enum-name="WhetherEnum"></es-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="searchForm">查询</el-button>
        <el-button icon="el-icon-refresh" @click="resetSearchForm">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
      <el-button type="primary" icon="el-icon-edit" @click="edit">修改</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="handleDelete">删除</el-button>
    </el-row>
    <!--表格-->
    <el-table
      border
      :data="tableData"
      v-loading="loading"
      element-loading-text="数据加载中"
      @selection-change="handleSelectionChange"
      class="mt-20">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>

      <el-table-column
        prop="roleCode"
        label="角色编码"
        width="150"
        show-overflow-tooltip
      >
      </el-table-column>

      <el-table-column
        prop="roleName"
        label="角色名称"
        width="150"
        show-overflow-tooltip
      >
      </el-table-column>

      <el-table-column
        prop="remark"
        label="备注"
        show-overflow-tooltip
      >
      </el-table-column>


      <el-table-column
        prop="isSys"
        label="是否系统内置"
        width="150">
        <template slot-scope="scope">
          <!--自定义组件 字典转义-->
          <es-value-format
            enum-name="WhetherEnum"
            :value="scope.row.isSys"
            render-color>
          </es-value-format>
        </template>
      </el-table-column>

      <el-table-column
        fixed="right"
        label="操作"
        show-overflow-tooltip
        width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="detail(scope.row)">查看
          </el-button>
          <el-button
            size="mini" type="primary"
            @click="edit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
            v-if="scope.row.isSys == 0"
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      style="margin: 20px;float: right;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-size="searchParam.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!--新增修改-->
    <el-dialog :title="title" :visible="action==='add' || action==='edit'" :before-close="handleClose">
      <el-form :model="item" :rules="rules" ref="ruleForm" label-width="100px">
        <div class="form-item-group">
          <el-form-item label="角色编码" prop="roleCode" >
            <el-input v-model="item.roleCode"
                      placeholder="请输入角色编码"
                      maxlength="50"
                      :disabled="action==='edit'"
                      show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="item.roleName"
                      placeholder="请输入角色名称"
                      maxlength="50"
                      show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="备注" prop="remark" >
            <el-input v-model="item.remark"
                      placeholder="请输入备注"
                      maxlength="250"
                      type="textarea"
                      :autosize="{ minRows: 4}"
                      show-word-limit
            ></el-input>
          </el-form-item>
        </div>
        <div class="form-item-group">
          <el-form-item label="授权" prop="menuIdList">
            <el-row>
              <el-button type="text" @click="handleExpandAll()">{{isExpand?'收起':'展开'}}</el-button>
            </el-row>
            <el-tree
              :data="menuList"
              show-checkbox
              :indent="32"
              ref="tree"
              node-key="value"
              @check-change="handleCheckChange">
            </el-tree>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="action = 'list'">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!--详情页-->
    <el-dialog :title="title" :visible="action==='info'" :before-close="handleClose">
      <el-form :model="item" label-width="100px">
        <div class="form-item-group">
          <el-form-item label="角色编码" prop="roleCode">
            <span>{{item.roleCode||"-"}}</span>
          </el-form-item>
          <el-form-item label="部门名称" prop="roleName">
            <span>{{item.roleName||"-"}}</span>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <span>{{item.remark||"-"}}</span>
          </el-form-item>

          <el-form-item label="系统内置">
            <es-value-format enum-name="WhetherEnum" :value="item.isSys" render-color></es-value-format>
          </el-form-item>
        </div>
        <div class="form-item-group">

        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="action = 'list'">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {getList, save, update, remove,getMenuIdList} from '../../api/sys/roleApi'
  import {treeData} from '../../api/sys/menuApi'
  import validate from '../../libs/validate'
  export default {
    name: 'role',
    data() {
      return {
        searchParam: {//表格数据请求参数
          page: 1,
          limit: 10
        },
        title: '',
        action: 'list',
        loading: false,
        item: {},  //修改/详情数据
        rules: {  //表单验证
          dictName: [
            {required: true, message: '请输入名称', trigger: 'blur'}
          ],
          sortNo: [
            {required: true, message: '请输入排序', trigger: 'blur'},
            {validator: validate.integer, trigger: 'blur'}
          ],
          status: [
            {required: true, message: '请选择状态', trigger: 'change'}
          ]
        },
        multipleSelection: [], //复选框选中的值
        tableData: [],
        total: 0,
        ids: [],
        menuList:[],
        isExpand:false//是否展开
      }
    },
    watch:{
      action:function (val) {
        let _this = this;
        if(val==="edit") {
          this.$nextTick(function () {
            //菜单全下下拉树回填
            getMenuIdList({roleId:_this.item.id}).then(res=>{
              if (res.code === 200) {
                for(let i=0;i<res.data.length;i++){
                  let node = _this.$refs.tree.getNode(res.data[i]);
                  if(node.data.children.length === 0){
                    _this.$refs.tree.setChecked(res.data[i],true)
                  }
                }
              } else {
                _this.$message.error(res.msg);
              }
            });
          })
        }

      }
    },
    mounted() {
      let _this = this;
      //获取数据
      this.getTableData();
      //获取菜单下拉树数据
      treeData({includeBtn:true}).then(res=>{
        if(res.code === 200){
          _this.menuList= res.data;
        }else{
          _this.$message.error(res.msg);
        }

      });
    },
    methods: {
      //选中菜单
      handleCheckChange:function() {
        let menuIdList = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
        this.item.menuIdList = menuIdList;
      },
      //全部展开/全部折叠
      handleExpandAll:function () {
        let _this = this;
        _this.isExpand=!_this.isExpand;
        let nodes = this.$refs.tree.store._getAllNodes();
        for(let i=0;i<nodes.length;i++){
          nodes[i].expanded=_this.isExpand;
        }

      },
      //获取数据
      getTableData() {
        let _this = this
        _this.loading = true
        getList(_this.searchParam).then((res) => {
          if (res.code === 200) {
            _this.tableData = res.data
            console.log(_this.tableData)
            _this.total = res.total
          } else {
            this.$message.error(res.msg)
          }
          _this.loading = false
        })
      },
      //提交表单
      submitForm() {
        let _this = this
        _this.$refs['ruleForm'].validate(function (valid) {
          if (valid) {
            //保存
            if (_this.action === 'add') {
              save(_this.item).then((res) => {
                if (res.code === 200) {
                  _this.$message.success('新增成功！');
                  _this.getTableData();
                  _this.action = 'list';
                } else {
                  _this.$message.error(res.msg);
                }

              })
            }
            //修改
            else if (_this.action === 'edit') {
              update(_this.item).then((res) => {
                if (res.code === 200) {
                  _this.$message.success('修改成功！')
                  _this.getTableData()
                } else {
                  _this.$message.error(res.msg)
                }
                _this.action = 'list'
              })
            }
          }
        })
      },
      //删除
      handleDelete: function (index, row) {
        let temp = Object.assign({}, row);
        //获取选中的id
        let ids = this.getSelectIds(temp);
        if (ids.length > 0) {
          this.ids = ids;
          //删除数据
          let _this = this;
          _this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            callback: function (action, instance) {
              if (action === "confirm") {
                remove(_this.ids).then((res) => {
                  if (res.code === 200) {
                    //刷新表格数据
                    _this.getTableData();
                    _this.$message.success("删除成功!");
                  }
                  else {
                    _this.$message.error(res.msg);
                  }
                })
                ;
              }
            }
          })
        }
      },
      add() {
        this.item = {}
        this.action = 'add'
        this.title = '新增角色'
      },
      //修改页面
      edit: function (index, row) {
        let _this = this
        let temp = Object.assign({}, row)
        if (Object.keys(temp).length === 0) {
          let chcekeds = _this.multipleSelection
          if (chcekeds.length === 0) {
            _this.$message.error('请选择一条数据')
            return false
          } else if (chcekeds.length > 1) {
            _this.$message.error('只能选择一条数据')
            return false
          } else {
            _this.item = chcekeds[0]
          }
        } else {
          _this.item = temp
        }
        _this.action = 'edit'
        _this.title = '修改角色'
        _this.currentIndex = index;
      },
      detail(row) {
        this.item = row;
        this.action = 'info';
      },
      handleClose(done) {
        this.action = 'list'
        done()
      },
      //获取选中行
      getSelectIds: function (row) {
        let chcekeds = [];
        let ids = [];
        if (!row || Object.keys(row).length === 0) {
          chcekeds = this.multipleSelection;
          if (chcekeds.length === 0) {
            this.$message.error("至少选择一条数据");
          } else {
            for (let key in chcekeds) {
              ids.push(chcekeds[key].id);
            }
          }
        } else {
          ids.push(row.id);
        }
        return ids;

      },
      //查询表格
      searchForm() {
        this.searchParam.page = 1
        //获取数据
        this.getTableData()
      },
      //重置查询表格
      resetSearchForm() {
        this.$refs['searchParam'].resetFields()
        //获取数据
        this.getTableData()
      },
      handleSizeChange(limit) {
        this.searchParam.limit = limit
        //获取数据
        this.getTableData()
      },
      handleCurrentChange(page) {
        this.searchParam.page = page
        //获取数据
        this.getTableData()
      },
      //复选框选择
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
    }
  }
</script>

<style scoped>

</style>
